import blue
import svc
import service
import base
import util
import uthread
import log
import sys
import _socket
import datetime
import os

class EveProcessHealthSvc(svc.processHealth):
    __guid__ = 'svc.eveProcessHealth'
    __replaceservice__ = 'processHealth'
    __servicename__ = 'eveProcessHealth'
    __displayname__ = 'Eve Process Health Service'

    def __init__(self, *args):
        svc.processHealth.__init__(self)
        self.lastLoggedLine = 0



    def LogDogma(self):
        if (boot.role == 'server'):
            maxModules = 0
            totalModules = 0
            avgModules = 0
            count = 0
            dogmaLag = [0]
            for (bindparam, dogmaLocation,) in sm.GetService('dogmaIM').boundObjects.items():
                effectList = dogmaLocation.effectManager.effectTimerList
                if effectList:
                    try:
                        dogmaLag.append((float((effectList[0][0] - blue.os.GetTime(1))) / float(const.SEC)))
                    except KeyError:
                        pass
                if (len(effectList) > maxModules):
                    maxModules = len(effectList)
                totalModules += len(effectList)

            mostLag = min(0, min(dogmaLag))
            self.logLines[-1].update({'solCounts': count,
             'maxModules': maxModules,
             'totalModules': totalModules,
             'dogmaLateness': (-1 * mostLag)})



    def DoOnceEvery10Secs(self):
        self.LogCpuMemNet()
        self.LogDogma()



    def DoOnceEvery10Minutes(self):
        self.WriteLog()



    def WriteLog(self):
        dumpPath = prefs.GetValue('ProcessHealthLogPath', None)
        if (dumpPath is None):
            self.LogInfo('Will not dump processhealth info since it is not configured in prefs (ProcessHealthLogPath)')
            return 
        computerName = blue.pyos.GetEnv().get('COMPUTERNAME', 'unknown')
        nodeID = sm.GetService('machoNet').GetNodeID()
        if (nodeID == None):
            nodeID = boot.role
        logLines = self.GetProcessInfo()
        txt = ''
        if (self.lastLoggedLine == 0):
            for name in logLines[0].iterkeys():
                txt += ('%s\t' % name)

            txt += '\n'
        for l in range(self.lastLoggedLine, (len(logLines) - 1)):
            logLine = logLines[l]
            for name in logLines[0].iterkeys():
                if (name in ('dateTime', 'pyDateTime')):
                    txt += ('%s\t' % util.FmtDate(logLine[name]))
                elif round(logLine[name], 2).is_integer():
                    txt += ('%s\t' % str(logLine[name]))
                else:
                    txt += ('%.4f\t' % logLine[name])

            txt += '\n'

        if not os.path.exists(dumpPath):
            os.mkdir(dumpPath)
        d = util.FmtDate(blue.os.GetTime(), 'sn')
        fileName = ('PHS %s %s %s.txt' % (computerName,
         nodeID,
         d))
        fileName = os.path.join(dumpPath, fileName.replace(':', '.').replace(' ', '.'))
        f = open(fileName, 'a+')
        f.write(txt)
        f.close()
        self.LogInfo(('Finished writing out %s entries from processHealth into %s' % (len(logLines), fileName)))
        self.lastLoggedLine = len(logLines)




